package com.example.user.controller;

import com.example.model.check_in.PasswordDo;
import com.example.model.response.Result;
import com.example.model.user.User;
import com.example.model.user.vo.LoginUserVo;
import com.example.core.utils.ServletUtils;
import com.example.user.utils.TokenWorker;
import com.example.user.service.MenuService;
import com.example.user.service.UserAuthService;
import com.example.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class UserAuthController {

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserAuthService userAuthService;

    @Autowired
    private TokenWorker tokenWorker;

    @GetMapping("/getInfo")
    public Result getInfo() {
        Map<String, Object> data = new HashMap<>();
        User loginUser = tokenWorker.getLoginUser(ServletUtils.getRequest()).getUser();
        data.put("name",loginUser.getNickName());
        data.put("avatar",loginUser.getAvatar());
        data.put("roles", userService.getUserRoleGroup(loginUser));
        data.put("authorities",menuService.getMenuPermsByUserId(loginUser.getUserId()));
        return Result.success(data);
    }

    @GetMapping("/getRouters")
    public Result getRouters() {
        User loginUser = tokenWorker.getLoginUser(ServletUtils.getRequest()).getUser();
        return Result.success(menuService.getRouters(loginUser.getUserId()));
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginUserVo loginUserVo){
        Map<String, Object> data = new HashMap<>();
        String token = userAuthService.login(loginUserVo.getUsername(),loginUserVo.getPassword());
        data.put("token", token);
        return Result.success("登录成功", data);
    }

    @GetMapping("/hasPerm")
    public Boolean hasPerm(@RequestParam("permission") String permission) {
        return userAuthService.hasPerm(permission, tokenWorker.getLoginUser(ServletUtils.getRequest()));
    }

    @GetMapping("/getUsername")
    public String getLoginUsername() {
        return userAuthService.getLoginUsername(tokenWorker.getLoginUser(ServletUtils.getRequest()));
    }

}
